package com.neusoft.EYSystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neusoft.EYSystem.dao.UserDAO;
import com.neusoft.EYSystem.po.*;
import com.neusoft.EYSystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    // 工具方法：判断是否为合法字符串（排除 null、空串、"null"）
    private boolean isValid(String value) {
        return value != null && !value.trim().isEmpty() && !"null".equalsIgnoreCase(value.trim());
    }

    @Autowired
    UserDAO userDAO;

    @Override
    public ResponseBean<User> getUser(User user) {
        User result = userDAO.getUser(user);
        ResponseBean<User> rb;
        if (result == null) {
            rb = new ResponseBean<>(500, "账号名或者手机号不存在");
        } else if (!user.getPassword().equals(result.getPassword())) {
            rb = new ResponseBean<>(500, "密码错误");
        }else if (!user.getRole().equals(result.getRole())){
            rb = new ResponseBean<>(500, "职位选择错误，您是" + result.getRole() + "，请重新登录");
        }else {
            rb = new ResponseBean<>(200, "登录成功");
            rb.setData(result);
        }
        return rb;
    }

    @Override
    public ResponseBean<List<User>> getUserByRole() {
        List<User> result = userDAO.getUserByRole();
        ResponseBean<List<User>> rb;
        if (result.isEmpty()) {
            rb = new ResponseBean<>(500, "当前暂无职工（健康管家）");
        } else {
            rb = new ResponseBean<>(200, "查询成功");
            rb.setData(result);
        }
        return rb;
    }

    @Override
    public PageResponseBean<List<User>> pageCareTakers(String username, String phone, Long page, Long size) {
        IPage<User> pageData = new Page<>(page, size);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("role", "caretaker");
        // 1. 判断是否传入 username 字段，进行模糊匹配 username LIKE '%xxx%'
        if (username != null && !username.trim().isEmpty()) {
            queryWrapper.like("username", username);
        }else {
            queryWrapper.isNotNull("username"); // 如果没有提供用户名，则查询所有健康管家
        }

        // 2. 判断是否传入 phone 字段，进行模糊匹配 phone LIKE '%xxx%'
        if (phone != null && !phone.trim().isEmpty()) {
            queryWrapper.like("phone", phone);
        }else {
            queryWrapper.isNotNull("phone"); // 如果没有提供手机号，则查询所有健康管家
        }
        IPage<User> userPage = userDAO.selectPage(pageData,queryWrapper);
        List<User> userList = userPage.getRecords();
        long total = userPage.getTotal();
        PageResponseBean<List<User>> responseBean = new PageResponseBean<>();
        if (userList.isEmpty()) {
            responseBean.setStatus(500);
            responseBean.setMsg("当前暂无健康管家");
        } else {
            responseBean.setStatus(200);
            responseBean.setMsg("查询成功");
            responseBean.setData(userList);
            responseBean.setTotal(total);
        }
        return responseBean;
    }

    @Override
    public PageResponseBean<List<User>> pageCareTakersByName(Long cur, Long number, User user) {
        // 1. 创建分页对象（第cur页，每页number条记录）
        IPage<User> page = new Page<>(cur, number);

        // 2. 构造查询条件的包装器，用于动态拼接SQL中的WHERE子句
        QueryWrapper<User> wrapper = new QueryWrapper<>();

        // 5. 判断是否传入 name 字段，进行模糊匹配 name LIKE '%xxx%'
        if (isValid(user.getUsername())) {
            wrapper.like("username", user.getUsername());
        }
        wrapper.eq("role","caretaker");

        IPage<User> result = userDAO.selectPage(page, wrapper);

        // 8. 获取分页结果的数据列表和总条数
        List<User> list = result.getRecords();
        long total = result.getTotal();
        // 9. 封装并返回统一的响应对象 PageResponseBean
        PageResponseBean<List<User>> rb;
        if (total > 0) {
            rb = new PageResponseBean<>(list); // 查询成功
            rb.setTotal(total);
        } else {
            rb = new PageResponseBean<>(500, "无健康管家数据"); // ⚠️ 不推荐使用500，查无数据不代表错误（建议返回空列表）
        }

        return rb;
    }

}
